<template>
  <div id='app'>
    <van-nav-bar
    title="登录"
    left-text="返回"
    left-arrow
    @click-left="onClickLeft"
  />
    <van-form @submit="onSubmit">
    <van-field
      v-model="form.phone"
      name="用户名"
      label="用户名"
      placeholder="请输入手机号"
      :rules="[
         {
           required: true,
           message: '请填写手机号'
         },
         {
           validator: phoneCheck,
           message: '格式有误，请重新输入'
         }
      ]"
    />
    <van-field
      v-model="form.password"
      type="password"
      name="密码"
      label="密码"
      placeholder="请输入密码"
      :rules="[
        {
          required: true,
          message: '请填写密码'
        },{
          pattern: /^[a-zA-Z0-9{6, 12}]/,
          message: '格式有误，请重新输入'
        }]"
    />
    <div style="margin: 16px;">
      <van-button round block
        type="info"
        native-type="submit"
        :loading="isLoading"
      >登录</van-button>
    </div>
  </van-form>
  </div>
</template>

<script>
import { login } from '@/services/user'

export default {
  name: 'Login',
  components: {},
  data () {
    return {
      // 登录按钮加载中的状态
      isLoading: false,
      form: {
        phone: '',
        password: ''
      }
    }
  },
  methods: {
    phoneCheck (value) {
      return /^1\d{10}$/.test(value)
    },
    async onSubmit () {
      // 内容通过校验以后，会触发
      this.isLoading = true
      console.log('submit')
      const { data } = await login(this.form)
      console.log(data)
      this.isLoading = false
      if (data.state === 1) {
        this.$toast.success('登录成功')
        // 存储到state中
        this.$store.commit('setUser', data.content)
        // 跳转到redirect
        this.$router.push(this.$route.query.redirect || '/')
      } else {
        this.$toast.fail('登录失败')
      }
    },
    onClickLeft () {
      this.$router.go(-1)
    }
  }
}

</script>
<style scoped>

</style>
